/*
This softtware use BSD licence (http://opensource.org/licenses/BSD-3-Clause)

Copyright (c) 2013, Martin Lebeda
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

3. Neither the name of the Martin Lebeda nor the names of its contributors may
be used to endorse or promote products derived from this software without
specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package cz.lebeda.bas;

import java.io.FileInputStream;
import java.io.FileOutputStream;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;


/**
 * Base application class.
 *
 * @author <a href="mailto:martin.lebeda@gmail.com">Martin Lebeda</a>
 *         Date: 11.11.13
 */
public class BasApp
{
    public static void main( String[] args ) throws Exception {
        Options options = getOptions();
        CommandLineParser parser = new GnuParser();
        CommandLine cmd = parser.parse( options, args);

        if (cmd.hasOption("h")) {
            showHelp(options);
            return; // only show help and exit
        }

        final VOConfig cfg;
        if (cmd.hasOption("config")) {
            Serializer serializer = new Persister();
            final String config = cmd.getOptionValue("config");
            FileInputStream fis = new FileInputStream(config);
            cfg = serializer.read(VOConfig.class, fis);
            fis.close();
        } else {
            cfg = new VOConfig();
        }

        cfg.setCmd(cmd);

        CipherProvider dataCipherProvider = new CipherProvider();
        dataCipherProvider.setPassword(cmd.getOptionValue("passwd", null));
        CipherProvider metaCipherProvider = new CipherProvider();
        metaCipherProvider.setPassword(cmd.getOptionValue("passwd-meta", null));

        String repoPathStr = cfg.getRepository();
        Repository repository = new Repository(repoPathStr, dataCipherProvider, metaCipherProvider);

        if (cmd.hasOption("dump-config")) {
            Serializer serializer = new Persister();
            final FileOutputStream fos = new FileOutputStream(cmd.getOptionValue("dump-config"));
            serializer.write(cfg, fos);
            fos.close();
        }
        
        if (cmd.hasOption("backup")) {
            BackupService backup = new BackupService(cfg, repository);
            backup.run();
        }

        if (cmd.hasOption("restore")) {
            //noinspection unchecked
            String restoreTo = null;
            if (cmd.hasOption("restore-to")) {
                restoreTo = cmd.getOptionValue("restore-to");
            }
            
            RestoreService restore = new RestoreService(cmd.getOptionValue("r"), repository, cmd.getArgList(), restoreTo);
            restore.run();
        }

        if (cmd.hasOption("check")) {
            CheckService check = new CheckService(cmd.getOptionValue("check"), repository);
            check.run();
        }
    }

    private static Options getOptions() {
        Options options = new Options();

        options.addOption("h", "help", false, "print this message" );

        //noinspection AccessStaticViaInstance
        options.addOption(OptionBuilder.withLongOpt("config")
                .withDescription("use configuration file for backup")
                .hasArg()
                .withArgName("XML")
                .create("c"));

        //noinspection AccessStaticViaInstance
        options.addOption(OptionBuilder.withLongOpt("dump-config")
                .withDescription("write configuration file for backup")
                .hasArg()
                .withArgName("XML")
                .create());

        //noinspection AccessStaticViaInstance
        options.addOption(OptionBuilder.withLongOpt("repository")
                .withDescription("path to backup repository")
                .hasArg()
                .withArgName("PATH")
                .create("p"));

        //noinspection AccessStaticViaInstance
        options.addOption(OptionBuilder.withLongOpt("passwd")
                .withDescription("paassword for AES encryption/decryption data")
                .hasArg()
                .withArgName("PASSWD")
                .create());

         //noinspection AccessStaticViaInstance
        options.addOption(OptionBuilder.withLongOpt("passwd-meta")
                .withDescription("paassword for AES encryption/decryption metadata (index of backuped files)")
                .hasArg()
                .withArgName("PASSWD")
                .create());

        /**************************************************************/

        //noinspection AccessStaticViaInstance
        options.addOption( OptionBuilder.withLongOpt("backup")
                .withDescription("create new backup of paths with ID")
                .hasArg()
                .withArgName("ID")
                .create("b"));

        //noinspection AccessStaticViaInstance
        options.addOption(OptionBuilder.withLongOpt("exclude")
                .withDescription("(only backup) exclude files with wildcard pattern ie: *.tmp *.bak")
                .hasArgs()
                .withArgName("PATERNS")
                .create());

        //noinspection AccessStaticViaInstance
        options.addOption( OptionBuilder.withLongOpt("exclude-dir")
                .withDescription("(only backup) exclude subdirectories with wildcard pattern")
                .hasArgs()
                .withArgName("PATERNS")
                .create());

        /**************************************************************/

        //noinspection AccessStaticViaInstance
        options.addOption( OptionBuilder.withLongOpt("restore")
                .withDescription("restore data from selected index")
                .hasArg()
                .withArgName("IDX")
                .create("r"));

        //noinspection AccessStaticViaInstance
        options.addOption(OptionBuilder.withLongOpt("restore-to")
                .withDescription("restore data to another path (tree structure is preserved)")
                .hasArg()
                .withArgName("TARGET_PATH")
                .create());

        /**************************************************************/

        //noinspection AccessStaticViaInstance
        options.addOption(OptionBuilder.withLongOpt("check")
                .withDescription("check exists data from index (can use wildcard in index name)")
                .hasOptionalArg()
                .withArgName("IDX")
                .create());

        // TODO Lebeda - --check check if exists all data files used in backup indexes
        // TODO Lebeda - checksum check if exists and are readable all data files used in backup indexes
        // TODO Lebeda - clear delete datafiles which not linked from any indexes

        /**************************************************************/

        // TODO Lebeda - -l --log <ID> <PATERN> list all files contains PATERN from indexes files for ID
        // TODO Lebeda - --list <ID> list all indexes for ID

        /**************************************************************/
        // TODO Lebeda - delete <IDX> delete the index files
        // TODO Lebeda - use automatic hostname as ID InetAddress.getLocalHost().getHostName()

        return options;
    }

    /**
     * Show help
     *
     * @param options instance of options
     */
    private static void showHelp(Options options) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp( "bas -p repository options path1 path2 ... \n"
                + "   paths are from disk for backup and from backup index for restore", options);
    }
}
